package com.module.overview.ui.editCardList

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.CardSettingModel
import com.common.base.widget.SCheckBox
import com.module.overview.R
import java.util.Collections

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/6/13
 *
 * 描述：卡片编辑列表适配器，支持拖拽排序和开关状态切换
 *
 * 修订历史：
 *
 */
class OverviewEditCardListAdapter(private val dragListener: OnStartDragListener) : 
    BaseQuickAdapter<CardSettingModel, BaseViewHolder>(R.layout.overview_item_edit_card_list),
    ItemTouchHelperAdapter {

    // 定义拖拽监听器接口
    interface OnStartDragListener {
        fun onStartDrag(viewHolder: BaseViewHolder)
    }

    // 定义开关状态变化监听器
    private var onSwitchChangeListener: ((position: Int, isEnabled: Boolean) -> Unit)? = null

    // 设置开关状态变化监听器
    fun setOnSwitchChangeListener(listener: (position: Int, isEnabled: Boolean) -> Unit) {
        onSwitchChangeListener = listener
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun convert(holder: BaseViewHolder, item: CardSettingModel) {
        // 设置卡片名称
        holder.setText(R.id.tvCardName, item.name)
        
        // 设置开关状态
        holder.getView<SCheckBox>(R.id.switchEnable).let {
            it.setChecked(item.isEnabled)
            // 设置开关状态变化监听
            it.setOnCheckedChangeListener(object : SCheckBox.OnCheckedChangeListener{
                override fun onCheckedChange(view: View?, isChecked: Boolean) {
                    val position = holder.bindingAdapterPosition
                    if (position != -1) {
                        val newState = !item.isEnabled
                        item.isEnabled = newState
                        onSwitchChangeListener?.invoke(position, newState)
                    }
                }

            })
        }
        
        // 设置拖拽图标触摸监听
        holder.getView<ImageView>(R.id.ivDrag).setOnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                dragListener.onStartDrag(holder)
            }
            false
        }
    }

    override fun onItemViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        super.onItemViewHolderCreated(viewHolder, viewType)
    }
    
    // 实现ItemTouchHelperAdapter接口的方法
    override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
        // 交换数据集中的项目
        Collections.swap(data, fromPosition, toPosition)
        // 通知适配器项目已移动
        notifyItemMoved(fromPosition, toPosition)
        // 更新排序顺序
        for (i in data.indices) {
            data[i].sortOrder = i
        }
        return true
    }
    
    override fun onDragComplete() {
        // 拖拽完成后可以在这里保存新的排序顺序
    }
}